/**
 * 
 */
package admin.mode;

import java.util.ArrayList;
import java.util.HashMap;

import base.PageList;
import base.Power;
import base.tools.Tools;

/**
 * @author qsj
 * 
 */
public class ResourceMode {
	@SuppressWarnings("unchecked")
	public ArrayList getTypeListById(Power power, String id) throws Exception {
		String sql = "select * from m_classify where parentid=" + id;
		return power.getListFromSql(sql);
	}

	@SuppressWarnings("unchecked")
	public HashMap getTypeMapById(Power power, AdminMode admin, String id)
			throws Exception {
		String sql = "select * from m_classify where classid=" + id;
		return power.getMapFromSql(sql);
	}

	@SuppressWarnings("unchecked")
	public HashMap getResListByTypeId(Power power, String typeId)
			throws Exception {
		String mediumid = power.getParameter("medium");// 媒体格式
		String restypeid = power.getParameter("restype");// 资源类型
		String deep = power.getParameter("deep");// 深度
		String state = power.getParameter("state");

		String keywords = power.getParameter("keywords");// 前台用
		String sql = "select * from m_material m,m_mat_classify mc,m_classify c,d_medium d where m.resourceid=mc.matid and mc.classid=c.classid and m.mediumid=d.mediumid ";
		if (deep.equals("1")) {
			sql += "and c.classid in (select classid from m_classify where classpath like '%>"
					+ typeId + ">%' or classid=" + typeId + ")";
		} else if (!typeId.equals("")) {
			sql += "and c.classid=" + typeId;
		}
		if (!mediumid.equals("")) {
			sql += " and m.MediumID in (select mediumid from d_medium where parentid="
					+ mediumid + " or mediumid=" + mediumid + ")";
		}
		if (!restypeid.equals("")) {
			sql += " and instr('" + getResTypeIdStrById(power, restypeid)
					+ "',m.restype)>0";
		}
		if (!state.equals("") && !state.equals("0")) {
			sql += " and state=" + state;
		}
		if (!keywords.equals("")) {
			sql += " and m.title like '%" + keywords + "%'";
		}
		PageList PL = new PageList();
		PL.setOnePage(20);
		PL.setEndForm(true);
		ArrayList list = new ArrayList();
		String sqlList = PL.getPageNums(power, sql.toString());
		list = power.getListFromSql(sqlList);
		power.debug(sqlList);
		HashMap map = new HashMap();
		map.put("list", list);
		map.put("PL", PL.getContent());
		map.put("PLend", PL.getEndButtonString());
		return map;
	}

	// 前台用
	@SuppressWarnings("unchecked")
	public HashMap getResListByTypeIdFront(Power power, String typeId)
			throws Exception {
		String mediumid = power.getParameter("medium");// 媒体格式
		String restypeid = power.getParameter("restype");// 资源类型
		String deep = power.getParameter("deep");// 深度
		String state = power.getParameter("stat");
		String keywordQueryMode = power.getParameter("keywordQueryMode");

		String keywords = power.getParameter("keywords");// 前台用

		String grades_id = power.getParameter("grades_id");
		String educations_id = power.getParameter("educations_id");
		String learners_id = power.getParameter("learners_id");
		String st = power.getParameter("st");
		String et = power.getParameter("et");
		String sql = "select * from m_material m,m_mat_classify mc,m_classify c,d_medium d where m.resourceid=mc.matid and mc.classid=c.classid and m.mediumid=d.mediumid ";
		if (deep.equals("1")) {
			sql += "and c.classid in (select classid from m_classify where classpath like '%>"
					+ typeId + ">%' or classid=" + typeId + ")";
		} else if (!typeId.equals("")) {
			sql += "and c.classid=" + typeId;
		}
		if (!mediumid.equals("")) {
			sql += " and m.MediumID in (select mediumid from d_medium where parentid="
					+ mediumid + " or mediumid=" + mediumid + ")";
		}
		if (!restypeid.equals("")) {
			sql += " and instr('" + getResTypeIdStrById(power, restypeid)
					+ "',m.restype)>0";
		}
		if (state.equals("4")) {
			sql += " and state=" + state;
		} else {
			sql += " and state in (3,4)";
		}
		if (!keywords.equals("")) {
			power.setAttribute("keywords", keywords);
			if (keywordQueryMode.equals("1")) {
				sql += " and m.title='" + keywords + "'";

			} else {
				sql += " and m.title like '%" + keywords + "%'";
			}
		}
		if (!grades_id.equals("")) {
			power.setAttribute("grades_id", grades_id);
			String[] grades_ids = base.tools.Tools.splitToArray(grades_id, ",");
			sql += " and (";
			for (int i = 0; i < grades_ids.length; i++) {
				sql += " m.Learners like '%," + grades_ids[i] + ",%'";
				if (i < grades_ids.length - 1)
					sql += " or ";
			}
			sql += ")";

		}
		if (!educations_id.equals("")) {
			power.setAttribute("educations_id", educations_id);
			String[] educations_ids = base.tools.Tools.splitToArray(
					educations_id, ",");
			sql += " and (";
			for (int i = 0; i < educations_ids.length; i++) {
				sql += " m.educations like '%," + educations_ids[i] + ",%'";
				if (i < educations_ids.length - 1)
					sql += " or ";
			}
			sql += ")";

		}
		if (!learners_id.equals("")) {
			power.setAttribute("learners_id", learners_id);
			String[] learners_ids = base.tools.Tools.splitToArray(learners_id,
					",");
			sql += " and (";
			for (int i = 0; i < learners_ids.length; i++) {
				sql += " m.learners like '%," + learners_ids[i] + ",%'";
				if (i < learners_ids.length - 1)
					sql += " or ";
			}
			sql += ")";

		}
		if (!st.equals("")) {
			power.setAttribute("st", st);
			sql += " and m.ImportTime>='" + st + " 00:00:00'";
		}
		if (!et.equals("")) {
			power.setAttribute("et", et);
			sql += " and m.ImportTime<='" + et + " 23:59:59'";
		}
		PageList PL = new PageList();
		PL.setOnePage(20);
		PL.setEndForm(true);
		ArrayList list = new ArrayList();
		String sqlList = PL.getPageNums(power, sql.toString());
		list = power.getListFromSql(sqlList);
		power.debug(sqlList);
		HashMap map = new HashMap();
		map.put("list", list);
		map.put("PL", PL.getContent());
		map.put("PLend", PL.getEndButtonString());
		return map;
	}

	@SuppressWarnings("unchecked")
	public String getResTypeIdStrById(Power power, String id) throws Exception {
		String result = "," + id;
		String sql = "select * from d_restype where parentid=" + id;
		ArrayList list = power.getListFromSql(sql);
		for (int i = 0; i < list.size(); i++) {
			result += "," + ((HashMap) list.get(i)).get("RESTYPEID");
		}
		return result + ",";
	}

	public boolean typeSave(Power power) throws Exception {
		String parentid = power.getParameter("parentid");
		String cname = power.getParameter("cname");
		String classpath = power.getParameter("classpath");
		String sql = "insert into m_classify set parentid=" + parentid
				+ ",cname='" + cname + "',classpath='" + classpath + "'";
		if (power.executeUpdate(sql) > -1) {
			if (!parentid.equals("0"))
				power
						.executeUpdate("update m_classify set childcount=childcount+1 where classid="
								+ parentid);// 父节点 childcount+1
			return true;
		}
		return false;
	}

	public boolean typeUpdate(Power power) throws Exception {
		String classid = power.getParameter("id");
		String cname = power.getParameter("cname");
		String sql = "update m_classify set cname='" + cname
				+ "' where classid=" + classid;
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public boolean typeDelete(Power power) throws Exception {// 传入ID实际只有一个
		String ids = power.getParameter("ids");
		HashMap map = power
				.getMapFromSql("select * from m_classify where classid=" + ids);
		if (!map.get("CHILDCOUNT").equals("0")) {// 有子节点不能删
			return false;
		}
		ArrayList list = power
				.getListFromSql("select * from m_mat_classify where classid="
						+ ids);
		if (list.size() > 0) {// 有内容不能删除
			return false;
		}
		String sql = "delete from m_classify where classid=" + ids;
		if (power.executeUpdate(sql) > -1) {
			String parentid = map.get("PARENTID").toString();
			if (!parentid.equals("0"))
				power
						.executeUpdate("update m_classify set childcount=childcount-1 where classid="
								+ parentid);// 父节点 childcount-1

			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public ArrayList getLanguagesList(Power power) throws Exception {
		String sql = "select * from d_language";
		return power.getListFromSql(sql);
	}

	@SuppressWarnings("unchecked")
	public ArrayList getResTypeListById(Power power, String id)
			throws Exception {
		String sql = "select * from d_restype where parentid=" + id;
		return power.getListFromSql(sql);
	}

	@SuppressWarnings("unchecked")
	public HashMap getResTypeMapById(Power power, String id) throws Exception {
		String sql = "select * from d_restype where restypeid=" + id;
		return power.getMapFromSql(sql);
	}

	@SuppressWarnings("unchecked")
	public ArrayList getMediumListById(Power power, String id) throws Exception {
		String sql = "select * from d_medium where parentid=" + id;
		return power.getListFromSql(sql);
	}

	@SuppressWarnings("unchecked")
	public HashMap getMediumMapById(Power power, String id) throws Exception {
		String sql = "select * from d_medium where mediumid=" + id;
		return power.getMapFromSql(sql);
	}

	@SuppressWarnings("unchecked")
	public ArrayList getEducationsList(Power power) throws Exception {
		String sql = "select * from d_edu";
		return power.getListFromSql(sql);
	}

	@SuppressWarnings("unchecked")
	public String getEducationsStr(Power power, String ids) throws Exception {
		String sql = "select * from d_edu where eduid in ('" + ids + "')";
		ArrayList list = power.getListFromSql(sql);
		String result = "";
		for (int i = 0; i < list.size(); i++) {
			HashMap map = (HashMap) list.get(i);
			result += map.get("SHOWNAME") + ",";
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public String getLanguagesStr(Power power, String ids) throws Exception {
		String sql = "select * from d_language where languageid in ('" + ids
				+ "')";
		ArrayList list = power.getListFromSql(sql);
		String result = "";
		for (int i = 0; i < list.size(); i++) {
			HashMap map = (HashMap) list.get(i);
			result += map.get("NAME") + ",";
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public String getGradesStr(Power power, String ids) throws Exception {
		String sql = "select * from d_grade where gradeid in ('" + ids + "')";
		ArrayList list = power.getListFromSql(sql);
		String result = "";
		for (int i = 0; i < list.size(); i++) {
			HashMap map = (HashMap) list.get(i);
			result += map.get("SHOWNAME") + ",";
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public String getLearnersStr(Power power, String ids) throws Exception {
		String sql = "select * from d_learner where learnerid in ('" + ids
				+ "')";
		ArrayList list = power.getListFromSql(sql);
		String result = "";
		for (int i = 0; i < list.size(); i++) {
			HashMap map = (HashMap) list.get(i);
			result += map.get("NAME") + ",";
		}
		return result;
	}

	public ArrayList<HashMap<String, String>> getLearnersList(Power power)
			throws Exception {
		String sql = "select * from d_learner";
		return power.getListFromSql(sql);
	}

	// 上传资源
	public boolean resSave(Power power, AdminMode admin) throws Exception {
		String resradio = power.getParameter("resradio");
		String local_url = power.getParameter("local_url");
		String net_url = power.getParameter("net_url");
		String title = power.getParameter("title");
		String cname_id = power.getParameter("cname_id");
		String keywords = power.getParameter("keywords");
		String restype_id = power.getParameter("restype_id");
		String educations_id = power.getParameter("educations_id");
		String languages_id = power.getParameter("languages_id");
		String grades_id = power.getParameter("grades_id");
		String medium_id = power.getParameter("medium_id");
		String learners_id = power.getParameter("learners_id");
		String descripe = power.getParameter("descripe");
		String filesize = power.getParameter("filesize").equals("") ? "0"
				: power.getParameter("filesize");

		String url = "";
		if (resradio.equals("local")) {
			url = local_url;
		} else {
			url = net_url;
		}

		String sql = "insert into m_material set " + "Title='" + title + "',"
				+ "Keywords='" + keywords + "'," + "Descripe='" + descripe
				+ "'," + "Userid=" + admin.getUserInfo().get("USERID") + ","
				+ "UserName='" + admin.getUserInfo().get("USERNAME") + "',"
				+ "URL='" + url + "'," + "Filesize=" + filesize + ","
				+ "MediumID='" + medium_id + "'," + "Languages='"
				+ languages_id + "'," + "Grades='" + grades_id + "',"
				+ "Learners='" + learners_id + "'," + "Educations='"
				+ educations_id + "'," + "state=1," + "PublishDate=now(),"
				+ "ImportTime=now()," + "ResType='," + restype_id + ",'";// 注意加,
		if (power.executeUpdate(sql) > -1) {// 插入资源表
			String lastId = power.getMapFromSql("SELECT LAST_INSERT_ID() id")
					.get("ID").toString();
			String sql1 = "insert into m_mat_classify set MatId=" + lastId
					+ ",ClassId=" + cname_id;
			power.executeUpdate(sql1);
			return true;
		}
		return false;
	}

	public boolean matClassifyDeletedByMatId(Power power, String id)
			throws Exception {
		String sql = "delete from m_mat_classify where MatId=" + id;
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	public boolean resDelete(Power power, AdminMode admin) throws Exception {
		String[] ids = power.getRequest().getParameterValues("ids");
		String str = base.tools.Tools.getStringFromStrings(ids, ",");
		String sql = "delete from m_material where resourceid in(" + str + ")";
		if (power.executeUpdate(sql) > -1) {
			for (int i = 0; i < ids.length; i++) {
				matClassifyDeletedByMatId(power, ids[i]);
			}
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public HashMap getResMapById(Power power, AdminMode admin, String id)
			throws Exception {
		String sql = "select * from m_material m,m_mat_classify mc where m.resourceid=mc.matid and resourceid="
				+ id;
		return power.getMapFromSql(sql);
	}

	// 上传资源
	public boolean resUpdate(Power power, AdminMode admin) throws Exception {
		String id = power.getParameter("id");

		String resradio = power.getParameter("resradio");
		String local_url = power.getParameter("local_url");
		String net_url = power.getParameter("net_url");
		String title = power.getParameter("title");
		String cname_id = power.getParameter("cname_id");
		String keywords = power.getParameter("keywords");
		String restype_id = power.getParameter("restype_id");
		String educations_id = power.getParameter("educations_id");
		String languages_id = power.getParameter("languages_id");
		String grades_id = power.getParameter("grades_id");
		String medium_id = power.getParameter("medium_id");
		String learners_id = power.getParameter("learners_id");
		String descripe = power.getParameter("descripe");
		String filesize = power.getParameter("filesize").equals("") ? "0"
				: power.getParameter("filesize");

		String url = "";
		if (resradio.equals("local")) {
			url = local_url;
		} else {
			url = net_url;
		}

		String sql = "update m_material set " + "Title='" + title + "',"
				+ "Keywords='" + keywords + "'," + "Descripe='" + descripe
				+ "'," + "Userid=" + admin.getUserInfo().get("USERID") + ","
				+ "UserName='" + admin.getUserInfo().get("USERNAME") + "',"
				+ "URL='" + url + "'," + "Filesize=" + filesize + ","
				+ "MediumID='" + medium_id + "'," + "Languages='"
				+ languages_id + "'," + "Learners='" + learners_id + "',"
				+ "Grades='" + grades_id + "'," + "Educations='"
				+ educations_id + "'," + "PublishDate=now(),"
				+ "ImportTime=now()," + "ResType='" + restype_id
				+ "' where resourceid=" + id;
		if (power.executeUpdate(sql) > -1) {
			String sql1 = "update m_mat_classify set ClassId=" + cname_id
					+ " where matid=" + id;
			power.executeUpdate(sql1);
			return true;
		}
		return false;
	}

	public boolean jpUpdate(Power power, AdminMode admin) throws Exception {
		String[] ids = power.getRequest().getParameterValues("ids");
		String str = base.tools.Tools.getStringFromStrings(ids, ",");
		String sql = "update m_material set state=4 where resourceid in(" + str
				+ ")";
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	public boolean nojpUpdate(Power power, AdminMode admin) throws Exception {
		String[] ids = power.getRequest().getParameterValues("ids");
		String str = base.tools.Tools.getStringFromStrings(ids, ",");
		String sql = "update m_material set state=3 where state=4 and resourceid in("
				+ str + ")";
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	public boolean shUpdate(Power power, AdminMode admin) throws Exception {
		String[] ids = power.getRequest().getParameterValues("ids");
		String str = base.tools.Tools.getStringFromStrings(ids, ",");
		String sql = "update m_material set state=3 where state=1 or state=2 and resourceid in("
				+ str + ")";
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	public boolean noshUpdate(Power power, AdminMode admin) throws Exception {
		String[] ids = power.getRequest().getParameterValues("ids");
		String str = base.tools.Tools.getStringFromStrings(ids, ",");
		String sql = "update m_material set state=2 where resourceid in(" + str
				+ ")";
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	public void updateViews(Power power, AdminMode admin, String id)
			throws Exception {
		power.executeUpdate("update m_material set views=views+1");
	}

	public void updateDowns(Power power, AdminMode admin, String id)
			throws Exception {
		power.executeUpdate("update m_material set downs=downs+1");
	}

	public String getParentClassName(Power power, AdminMode admin,
			String classpath) throws Exception {
		String result = "";
		String[] ids = base.tools.Tools.splitToArray(classpath, ">");
		for (int i = 0; i < ids.length; i++) {
			if (!ids[i].equals("0")) {
				result += getTypeMapById(power, admin, ids[i]).get("CNAME")
						+ ">";
			}
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public HashMap getVirtualpath(Power power, String vid) throws Exception {
		return power
				.getMapFromSql("select * from s_virtualpath where VirtualId="
						+ vid);
	}

	@SuppressWarnings("unchecked")
	public String getAllPath(Power power, HashMap resource, int type)
			throws Exception {
		String virtualPathStr = resource.get("VIRTUALID").toString();
		String URLStr = resource.get("URL").toString();
		HashMap virtual = getVirtualpath(power, virtualPathStr);
		String ret = null;
		if (!virtualPathStr.equals("") && !URLStr.equals("")) {
			ret = buildMaterialPath(virtual, URLStr, type);

		}
		return ret;

	}

	@SuppressWarnings("unchecked")
	private String buildMaterialPath(HashMap virtual, String subjectSpaceUrl,
			int pathType) throws Exception {
		return buildPath(virtual, subjectSpaceUrl, pathType, null);
	}

	@SuppressWarnings("unchecked")
	private String buildPath(HashMap virtual, String subjectSpaceUrl,
			int pathType, String additionalPath) throws Exception {
		String ret = null;
		StringBuffer buf = new StringBuffer();
		switch (pathType) {
		default:
			break;

		case 0: // '\0'
			buf.append(virtual.get("ABSOLUTEPATH")).append(subjectSpaceUrl);
			if (additionalPath != null)
				buf.append(additionalPath);
			ret = buf.toString();
			ret = Tools.transferFileSeperator(ret, "local");
			break;

		case 1: // '\001'
			buf.append("http://").append(virtual.get("HOSTIP")).append(":")
					.append(virtual.get("HTTPPORT")).append(
							virtual.get("VIRTUALPATH")).append(subjectSpaceUrl);
			if (additionalPath != null)
				buf.append(additionalPath);
			ret = buf.toString();
			ret = Tools.transferFileSeperator(ret, "http");
			break;

		case 2: // '\002'
			buf.append("ftp://").append(virtual.get("HOSTIP")).append(":")
					.append(virtual.get("FTPPORT")).append(
							virtual.get("VIRTUALPATH")).append(subjectSpaceUrl);
			if (additionalPath != null)
				buf.append(additionalPath);
			ret = buf.toString();
			ret = Tools.transferFileSeperator(ret, "http");
			break;

		case 3: // '\003'
			// buf.append(SysConfig.getWebContext()).append(SysConfig.getSpacePath()).append(virtual.getVirtualPath()).append(subjectSpaceUrl);
			buf.append("/tjresnew").append(virtual.get("VIRTUALPATH")).append(
					subjectSpaceUrl);
			if (additionalPath != null)
				buf.append(additionalPath);
			ret = buf.toString();
			ret = Tools.transferFileSeperator(ret, "http");
			break;

		case 4: // '\004'
			buf.append("mms://").append(virtual.get("HOSTIP")).append(
					virtual.get("VIRTUALPATH")).append(subjectSpaceUrl);
			if (additionalPath != null)
				buf.append(additionalPath);
			ret = buf.toString();
			ret = Tools.transferFileSeperator(ret, "http");
			break;
		}
		return ret;
	}

	@SuppressWarnings("unchecked")
	public HashMap getReview(Power power, AdminMode admin, String resid)
			throws Exception {
		String sql = "select * from m_review where resid=" + resid;
		PageList PL = new PageList();
		PL.setOnePage(20);
		PL.setEndForm(true);
		PL.setDefaultOrder("ReviewId desc");
		ArrayList list = new ArrayList();
		String sqlList = PL.getPageNums(power, sql.toString());
		list = power.getListFromSql(sqlList);
		HashMap map = new HashMap();
		map.put("list", list);
		map.put("PL", PL.getContent());
		map.put("PLend", PL.getEndButtonString());
		return map;
	}

	public boolean reviewDelete(Power power, AdminMode admin, String reviewid)
			throws Exception {
		String sql = "delete from m_review where reviewid=" + reviewid
				+ " and Reviewer='" + admin.getUserInfo().get("USERNAME") + "'";
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	public boolean reviewSave(Power power, AdminMode admin) throws Exception {
		String resid = power.getParameter("resid");
		String reviewer = power.getParameter("reviewer");
		String title = power.getParameter("title");
		String content = power.getParameter("content");
		String sql = "insert into m_review (Resid,Reviewer,Title,Content,Reviewtime) values ("
				+ resid
				+ ",'"
				+ reviewer
				+ "','"
				+ title
				+ "','"
				+ content
				+ "',now())";
		if (power.executeUpdate(sql) > -1) {
			return true;
		}
		return false;
	}

	public String getCountReview(Power power, AdminMode admin, String resid)
			throws Exception {
		return power.getMapFromSql(
				"select count(*) num from m_review where resid=" + resid).get(
				"NUM").toString();
	}

}
